/**
 * 打印插件
 * @param {*} _ref 可选参数：{
 *  id: '局部打印节点id',
 *  popTitle: '标题'
 * }
 * @author useryxl
 * @returns
 */
const Print = function(_ref) {
  this.options = _ref
  this.open()
}

Print.prototype = {
  docType() {
    // 暂时为html5
    return '<!DOCTYPE html>'
  },
  getHead() {
    const title = this.options.popTitle || document.title
    const pageSize = this.options.pageSize
    let links = ''
    let style = ''

    if (pageSize === 'portrait') {
      style += ' @page { size: portrait !important; } '
    } else if (pageSize === 'landscape') {
      style += ' @page { size: landscape !important; } '
    }

    // 复制所有link标签
    [].forEach.call(document.querySelectorAll('link'), function(item) {
      if (item.href.indexOf('.css') >= 0) {
        links += `<link type="text/css" rel="stylesheet" href="${item.href}" >`
      }
    })
    // 循环获取style标签的样式
    const domStyle = document.styleSheets
    if (domStyle && domStyle.length > 0) {
      for (let i = 0; i < domStyle.length; i++) {
        try {
          if (domStyle[i].cssRules || domStyle[i].rules) {
            const rules = domStyle[i].cssRules || domStyle[i].rules
            for (let b = 0; b < rules.length; b++) {
              style += rules[b].cssText
            }
          }
        } catch (e) {
          console.log(domStyle[i].href + e)
        }
      }
    }
    return `<head><title>${title}</title>${links}<style type="text/css">${style}</style></head>`
  },
  getBody() {
    let id = this.options.id
    id = id.replace(new RegExp('#', 'g'), '')
    const elsdom = this.beforeHanler(document.getElementById(id))
    const ele = this.getFormData(elsdom)
    const htm = ele.outerHTML
    return '<body>' + htm + '</body>'
  },
  // 处理canva转成图片
  beforeHanler(elsdom) {
    const canvasList = elsdom.querySelectorAll('canvas')
    // canvas转换png图片
    for (let i = 0; i < canvasList.length; i++) {
      if (!canvasList[i].style.display) {
        const _parent = canvasList[i].parentNode
        const _canvasUrl = canvasList[i].toDataURL('image/png')
        const _img = new Image()
        _img.className = 'canvasImg'
        _img.style.display = 'none'
        _img.src = _canvasUrl
        _parent.appendChild(_img)
      }
    }
    return elsdom
  },
  // 根据type去处理form表单
  getFormData(ele) {
    const copy = ele.cloneNode(true)
    const copiedInputs = copy.querySelectorAll('input,select,textarea')
    const canvasImgList = copy.querySelectorAll('.canvasImg,canvas')
    let selectCount = -1
    // 处理所有canvas
    for (let i = 0; i < canvasImgList.length; i++) {
      const _parent = canvasImgList[i].parentNode
      const item = canvasImgList[i]
      // 删除克隆后的canvas节点
      if (item.tagName.toLowerCase() === 'canvas') {
        _parent.removeChild(item)
      } else {
        item.style.display = 'block'
      }
    }
    // 处理所有输入框
    for (let i = 0; i < copiedInputs.length; i++) {
      const item = copiedInputs[i]
      let typeInput = item.getAttribute('type')
      const copiedInput = copiedInputs[i]
      // 获取select标签
      if (!typeInput) {
        typeInput = item.tagName === 'SELECT' ? 'select' : item.tagName === 'TEXTAREA' ? 'textarea' : ''
      }
      // 处理input框
      if (item.tagName === 'INPUT') {
        // 除了单选框 多选框比较特别
        if (typeInput === 'radio' || typeInput === 'checkbox') {
          if (item.checked) {
            copiedInput.setAttribute('checked', item.checked)
          }
        } else {
          copiedInput.value = item.value
          copiedInput.setAttribute('value', item.value)
        }
        // 处理select
      } else if (typeInput === 'select') {
        selectCount++
        for (let b = 0; b < ele.querySelectorAll('select').length; b++) {
          const select = ele.querySelectorAll('select')[b] // 获取原始层每一个select
          !select.getAttribute('newbs') && select.setAttribute('newbs', b) // 添加标识
          if (select.getAttribute('newbs') === selectCount) {
            const opSelectedIndex = ele.querySelectorAll('select')[selectCount].selectedIndex
            item.options[opSelectedIndex].setAttribute('selected', true)
          }
        }
        // 处理textarea
      } else {
        copiedInput.innerHTML = item.value
        copiedInput.setAttribute('html', item.value)
      }
    }

    return copy
  },
  open() {
    const tab = window.open('', 'Avue打印插件')
    tab.document.open()
    tab.document.write((`${this.docType()}<html>${this.getHead()}${this.getBody()}</html>`))
    setTimeout(function() {
      tab.window.print()
      tab.close()
    }, 100)
  }
}

export default Print
